// 页面：学情详情/单科报告
// 封装检查学情页面所需的接口与数据处理，便于维护

import http from '../utils/http.js'

const API_PATHS = {
  GET_STUDENT_ANALYSIS: '/jsonrest/mobile/score/AnalysisReportScore/0/getStudentAnalysis',
  FIND_STUDENT_SCORE_INFO: '/jsonrest/mobile/score/AnalysisReportScore/0/findStudentScoreInfo',
  FIND_XDJP_FOR_ALL: '/jsonrest/mobile/score/AnalysisReportScore/0/findXDJPForAll',
  FIND_SUBJECT_DIFFICULTY: '/jsonrest/mobile/score/AnalysisReportScore/0/findStudentAnalysisSubjectDifficulty',
  GET_KNOWLEDGE_ANALYSIS: '/jsonrest/mobile/score/AnalysisReportScore/0/getKnowledgePointAnalysis'
}

const EXAM_TYPE_LABEL_MAP = {
  1: '单元测试',
  2: '统考联考',
  3: '校内考试'
}

const SCORE_LEVEL_MAP = {
  A: { label: '优秀', color: '#0ED1AD' },
  B: { label: '良好', color: '#F3BF7E' },
  C: { label: '及格', color: '#FB850A' },
  D: { label: '低分', color: '#FA5940' }
}

export const getStudentAnalysis = (examId) => {
  if (!examId) {
    throw new Error('[getStudentAnalysis] examId不能为空')
  }
  return http.get(API_PATHS.GET_STUDENT_ANALYSIS, { examId })
}

export const findStudentScoreInfo = ({ examId, courseId } = {}) => {
  if (!examId) {
    throw new Error('[findStudentScoreInfo] examId不能为空')
  }

  const params = { examId }
  const hasCourseId = courseId !== undefined && courseId !== null

  if (hasCourseId) {
    params.courseId = courseId
  }

  return http.get(API_PATHS.FIND_STUDENT_SCORE_INFO, params)
}

export const findXDJPForAll = ({ examId, examType } = {}) => {
  if (!examId) {
    throw new Error('[findXDJPForAll] examId不能为空')
  }
  if (examType === undefined || examType === null || `${examType}`.trim() === '') {
    throw new Error('[findXDJPForAll] examType不能为空')
  }

  return http.get(API_PATHS.FIND_XDJP_FOR_ALL, {
    examId,
    examType
  })
}

export const mapAnalysisData = (analysisRes = {}, options = {}) => {
  const entity = analysisRes?.entity || {}
  const examTypeLabel = EXAM_TYPE_LABEL_MAP[entity.examType] || ''
  const rawList = Array.isArray(entity.analysisReportScoreVOs)
    ? entity.analysisReportScoreVOs
    : []

  const currentExam = {
    id: entity.exam_id || '',
    title: entity.exam_name || '',
    category: rawList.length > 1
      ? '全科'
      : (rawList[0]?.cours_name || '—'),
    range: examTypeLabel,
    date: entity.exam_time || ''
  }

  const subjectScores = rawList.map((item, index) => {
    const courseId = item.course_id || item.cours_id || index
    const scoreRaw = item.score ?? item.score_value ?? item.course_score ?? ''
    const totalRaw = item.full_socre ?? item.full_score ?? item.total_score ?? ''

    const scoreValue = Number(scoreRaw)
    const totalValue = Number(totalRaw)

    const hasValidScore = typeof scoreRaw !== 'object' && scoreRaw !== '' && !Number.isNaN(scoreValue)
    const hasValidTotal = typeof totalRaw !== 'object' && totalRaw !== '' && !Number.isNaN(totalValue) && totalValue > 0

    const safeScore = hasValidScore ? scoreValue : 0
    const safeTotal = hasValidTotal ? totalValue : 0

    const scoreRatio = hasValidTotal
      ? Math.max(Math.min(safeScore / safeTotal, 1), 0)
      : 0

    const scoreLevel = (item.score_level || '').toUpperCase()
    const levelConfig = SCORE_LEVEL_MAP[scoreLevel] || {}

    return {
      id: courseId,
      name: item.cours_name || `科目${index + 1}`,
      score: hasValidScore ? safeScore : null,
      scoreText: hasValidScore ? `${safeScore}` : (scoreRaw || '0'),
      totalScore: hasValidTotal ? safeTotal : null,
      totalScoreText: hasValidTotal ? `${safeTotal}` : (totalRaw || '0'),
      scoreRatio,
      scoreLevel,
      scoreLevelLabel: levelConfig.label || scoreLevel || '—',
      scoreColor: levelConfig.color || '#68708A',
      raw: item
    }
  })

  if (options.enableStorage) {
    uni.setStorageSync('checkingLearningStatus:analysisEntity', entity)
  }

  return {
    entity,
    currentExam,
    subjectScores,
    examScore: entity.score,
    examFullScore: entity.full_score,
    answerDetailUrls: subjectScores.map(subject => ({
      url: '/subpackages/student-functions/answerDetails',
      subject
    })),
    showRadar: subjectScores.length > 1
  }
}

export const mapScoreInfoData = (scoreInfoRes = {}) => {
  const entity = scoreInfoRes?.entity || {}
  return {
    entity,
    totalScore: entity.score ?? entity.totalScore ?? 0,
    totalScoreSum: entity.sum ?? entity.totalScoreSum ?? 0,
    gradeRank: entity.gradeRanking,
    classRank: entity.classRanking ?? entity.clazzRanking
  }
}

export const mapXdjpData = (xdjpRes = {}) => {
  const entity = xdjpRes?.entity
  if (entity === undefined || entity === null || entity === '') {
    return {
      content: '暂无点评'
    }
  }

  return {
    content: typeof entity === 'string'
      ? entity
      : (entity.xdjp ?? entity.comment ?? '暂无点评')
  }
}

export const restorePrefetchedData = (examId) => {
  const stored = uni.getStorageSync('checkingLearningStatus:prefetched')
  if (!stored || stored.examId !== examId) {
    return null
  }
  return stored
}

export const prefetchExamDetail = async ({ examId, examType, courseId = 0 } = {}) => {
  if (!examId) {
    console.warn('[prefetchExamDetail] examId缺失，跳过预请求')
    return null
  }

  const requests = [
    getStudentAnalysis(examId),
    findStudentScoreInfo({ examId, courseId }),
    examType !== undefined && examType !== null && `${examType}`.trim() !== ''
      ? findXDJPForAll({ examId, examType })
      : Promise.resolve(null)
  ]

  const [analysisRes, scoreInfoRes, xdjpRes] = await Promise.all(requests)

  const prefetched = {
    examId,
    examType,
    courseId,
    analysisRes,
    scoreInfoRes,
    xdjpRes
  }

  uni.setStorageSync('checkingLearningStatus:prefetched', prefetched)

  return prefetched
}

export const clearPrefetchedData = () => {
  uni.removeStorageSync('checkingLearningStatus:prefetched')
}

export const getSubjectDifficulty = ({ examId, examType, courseId, scoreId }) => {
  if (!examId) throw new Error('[getSubjectDifficulty] examId不能为空')
  if (examType === undefined || examType === null || `${examType}`.trim() === '') throw new Error('[getSubjectDifficulty] examType不能为空')
  if (!courseId) throw new Error('[getSubjectDifficulty] courseId不能为空')
  if (!scoreId) throw new Error('[getSubjectDifficulty] scoreId不能为空')

  return http.get(API_PATHS.FIND_SUBJECT_DIFFICULTY, {
    examId,
    examType,
    courseId,
    scoreId
  })
}

export const getKnowledgePointAnalysis = ({ scoreId, lId }) => {
  if (!scoreId) throw new Error('[getKnowledgePointAnalysis] scoreId不能为空')
  if (!lId) throw new Error('[getKnowledgePointAnalysis] lId不能为空')

  return http.get(API_PATHS.GET_KNOWLEDGE_ANALYSIS, {
    scoreId,
    l_id: lId
  })
}

export const mapSubjectDifficulty = (response = {}) => {
  const list = Array.isArray(response?.entity?.listVOs)
    ? response.entity.listVOs
    : Array.isArray(response?.entity?.resultList)
      ? response.entity.resultList
      : []

  return list.map((item, index) => ({
    id: item.id || index,
    difficulty: item.subject_difficulty_name || item.difficulty_name || item.difficulty || `难度${index + 1}`,
    myRate: Number(item.score_rate ?? item.myRate ?? item.my_rate ?? 0),
    avgRate: Number(item.score_rate_avg ?? item.avgRate ?? item.avg_rate ?? item.score_rate ?? 0)
  }))
}

export const mapKnowledgeAnalysis = (response = {}) => {
  const list = Array.isArray(response?.entity) ? response.entity : []

  const masteredCount = list.reduce((count, item) => count + (item.mastered ? 1 : 0), 0)

  const knowledgeData = list.map((item, index) => ({
    id: item.id || index,
    name: item.name || item.knowledge_name || `知识点${index + 1}`,
    value: Number(item.rate ?? item.percent ?? 0),
    color: item.color || ['#0ED1AD', '#F3BF7E', '#FB850A', '#FA5940'][index % 4],
    detail: item.detail || item.description || ''
  }))

  return {
    masteredCount,
    knowledgeData
  }
}

const ensureExamEntity = (analysisRes) => {
  if (analysisRes?.entity) {
    return analysisRes.entity
  }
  const stored = uni.getStorageSync('checkingLearningStatus:analysisEntity')
  if (stored) {
    return stored
  }
  throw new Error('[prefetchSubjectReport] 缺少考试分析实体数据，请先调用getStudentAnalysis')
}

export const prefetchSubjectReport = async ({ exam, subject, analysisEntity, examType, examId, courseId, scoreId, lId } = {}) => {
  const entity = analysisEntity || ensureExamEntity({ entity: exam })
  const resolvedExamId = examId || entity?.exam_id
  const resolvedExamType = examType ?? entity?.examType

  if (!subject && (!courseId || !scoreId)) {
    throw new Error('[prefetchSubjectReport] 缺少科目信息，无法预取单科报告数据')
  }

  const resolvedCourseId = courseId || subject?.id || subject?.cours_id || subject?.raw?.cours_id
  const resolvedScoreId = scoreId || subject?.raw?.score_id || subject?.score_id
  const resolvedKnowledgeId = lId || subject?.raw?.paper_id || subject?.paper_id

  if (!resolvedExamId) throw new Error('[prefetchSubjectReport] examId为空')
  if (resolvedExamType === undefined || resolvedExamType === null) throw new Error('[prefetchSubjectReport] examType为空')
  if (!resolvedCourseId) throw new Error('[prefetchSubjectReport] courseId为空')
  if (!resolvedScoreId) throw new Error('[prefetchSubjectReport] scoreId为空')
  if (!resolvedKnowledgeId) throw new Error('[prefetchSubjectReport] l_id为空')

  const requests = [
    findStudentScoreInfo({ examId: resolvedExamId, courseId: resolvedCourseId }),
    getSubjectDifficulty({
      examId: resolvedExamId,
      examType: resolvedExamType,
      courseId: resolvedCourseId,
      scoreId: resolvedScoreId
    }),
    getKnowledgePointAnalysis({
      scoreId: resolvedScoreId,
      lId: resolvedKnowledgeId
    })
  ]

  const [scoreInfoRes, difficultyRes, knowledgeRes] = await Promise.all(requests)

  console.log('单科报告-成绩信息:', scoreInfoRes)
  console.log('单科报告-难易得分率:', difficultyRes)
  console.log('单科报告-知识点分析:', knowledgeRes)

  const subjectReportPayload = {
    examId: resolvedExamId,
    examType: resolvedExamType,
    courseId: resolvedCourseId,
    scoreId: resolvedScoreId,
    lId: resolvedKnowledgeId,
    scoreInfoRes,
    difficultyRes,
    knowledgeRes,
    meta: {
      subjectName: subject?.name || subject?.cours_name || '',
      examName: entity?.exam_name || ''
    }
  }

  uni.setStorageSync('checkingLearningStatus:subjectReportPrefetched', subjectReportPayload)

  return subjectReportPayload
}

export const restoreSubjectReport = () => {
  return uni.getStorageSync('checkingLearningStatus:subjectReportPrefetched') || null
}

export const clearSubjectReport = () => {
  uni.removeStorageSync('checkingLearningStatus:subjectReportPrefetched')
}

export const useCheckingLearningStatusApi = () => ({
  getStudentAnalysis,
  findStudentScoreInfo,
  findXDJPForAll,
  mapAnalysisData,
  mapScoreInfoData,
  mapXdjpData,
  prefetchExamDetail,
  restorePrefetchedData,
  clearPrefetchedData,
  getSubjectDifficulty,
  getKnowledgePointAnalysis,
  mapSubjectDifficulty,
  mapKnowledgeAnalysis,
  prefetchSubjectReport,
  restoreSubjectReport,
  clearSubjectReport
})

export default {
  getStudentAnalysis,
  findStudentScoreInfo,
  findXDJPForAll,
  mapAnalysisData,
  mapScoreInfoData,
  mapXdjpData,
  prefetchExamDetail,
  restorePrefetchedData,
  clearPrefetchedData,
  getSubjectDifficulty,
  getKnowledgePointAnalysis,
  mapSubjectDifficulty,
  mapKnowledgeAnalysis,
  prefetchSubjectReport,
  restoreSubjectReport,
  clearSubjectReport,
  useCheckingLearningStatusApi
}
